package main

import (
	"os"
	"strconv"
	"strings"

	"github.com/BurntSushi/toml"
)

type biliUserInfo struct {
	UserName     string
	AccessToken  string
	RefreshToken string
	Cookie       string
}

type To struct {
	BiliUser []biliUserInfo
}

var BiliUsers []biliUserInfo
var path string = "./watchBLive.toml"

func (T *To) WriteToml() {
	f, err := os.Create(path)
	if err != nil {
		print(err)
		return
	}
	if err := toml.NewEncoder(f).Encode(T); err != nil {
		print(err)
		return
	}
}

func ReadTomlBili() (config *To, err error) {
	if _, err := os.Stat(path); err != nil {
		s := To{}
		s.WriteToml()
	}
	_, err = toml.DecodeFile(path, &config)
	return
}
func (T *To) AddUser() {
	code, user := Login()
	if code != 0 {
		print("添加用户失败")
		return
	}
	T.BiliUser = append(T.BiliUser, user)
	T.WriteToml()
}

func cookie2uid(cookie string) (uid int) {
	a := strings.Index(cookie, "DedeUserID=")
	if a >= 0 {
		b := cookie[a+len("DedeUserID="):]
		c := strings.Index(b, ";")
		u := b[:c]
		uid, _ = strconv.Atoi(u)
	}
	return
}
func cookie2csrf(cookie string) (csrf string) {
	a := strings.Index(cookie, "bili_jct=")
	if a == -1 {
		return
	}
	if len(cookie) < a+10 {
		return
	}
	b := cookie[a+9:]
	a = strings.Index(b, ";")
	if a == -1 {
		return
	}
	csrf = b[:a]
	return
}

func cookie2buvid(cookie string) (buvid string) {
	a := strings.Index(cookie, "BUVID=")
	if a == -1 {
		return
	}
	if len(cookie) < a+7 {
		return
	}
	b := cookie[a+6:]
	a = strings.Index(b, ";")
	if a == -1 {
		return
	}
	buvid = b[:a]
	return
}
